//
//  FavoritManager.m
//  iMiniTao
//
//  Created by liunian on 13-8-19.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "FavoritManager.h"
#import "FavorityEntity.h"
#import "Favorit.h"

@interface FavoritManager (){
    MKEnvObserverCenter    *_obCenter;
}

@end
static FavoritManager * sharedManager;
@implementation FavoritManager

+ (FavoritManager *)sharedManager{
    if (!sharedManager) {
        sharedManager = [[FavoritManager alloc] init];
    }
    return sharedManager;
}
- (id)init
{
    self = [super init];
    if (self) {
        _obCenter = [[MKEnvObserverCenter alloc] init];
    }
    return self;
}
- (void)addObserver:(id<FavoritManagerDelegate>)observer
{
    [_obCenter addEnvObserver:observer];
}

- (void)removeObserver:(id<FavoritManagerDelegate>)observer
{
    [_obCenter removeEnvObserver:observer];
}

- (void )getFavorites{
    NSArray *fetchArray = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FavorityEntity"
                                              inManagedObjectContext:self.managedObjectContext];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortid"
                                                                   ascending:YES];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    
    fetchRequest.fetchLimit = 100;
    fetchRequest.fetchOffset = 0;
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    [fetchRequest setIncludesPendingChanges:YES];
    
    fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if (fetchArray.count == 0) {
        [_obCenter noticeObervers:@selector(mkManagerFavoritesDidFinishedWithFavorites:)
                       withObject:nil];
    }
    _favorites = [[NSMutableArray alloc] initWithCapacity:fetchArray.count];
    
    for (int i = 0; i < [fetchArray count]; i++) {
        FavorityEntity *entity = [fetchArray objectAtIndex:i];
        CuzyTBKItem *item = [[CuzyTBKItem alloc] init];
        item.itemID = entity.itemID;
        item.itemName = entity.itemName;
        item.itemPrice = entity.itemPrice;
        item.itemImageURLString = entity.itemImageURLString;
        item.itemClickURLString = entity.itemClickURLString;
        item.promotionPrice = entity.promotionPrice;
        item.tradingVolumeInThirtyDays = entity.tradingVolumeInThirtyDays;
    
        Favorit *fav = [[Favorit alloc] init];
        fav.item = item;
        fav.index = [entity.sortid integerValue];
        [_favorites addObject:fav];
    }
    
    [_obCenter noticeObervers:@selector(mkManagerFavoritesDidFinishedWithFavorites:)
                   withObject:_favorites];
}

- (FavorityEntity *)getFavorityEntityWithItemName:(NSString *)name{
    
    FavorityEntity  *uEntity = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FavorityEntity"
                                              inManagedObjectContext:self.managedObjectContext];
    NSPredicate *predicate;
    predicate = [NSPredicate predicateWithFormat:@"(itemName == %@)",name];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setIncludesPendingChanges:YES];
    
    NSArray * fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if ([fetchArray count]>0) {
        uEntity = [fetchArray lastObject];
    }
    return uEntity;
}

- (void)reorderFavorites{
    if (!_favorites && _favorites.count<= 0) {
        return;
    }
    for (int i = 0; i < [_favorites count]; i++) {
        Favorit *obj = [_favorites objectAtIndex:i];
        [obj setIndex:i];
        [self saveFavorit:obj];
    }
}

- (BOOL)isFavorit:(CuzyTBKItem *)item{
    FavorityEntity *entity = [self getFavorityEntityWithItemName:item.itemName];
    if (entity) {
        return YES;
    }
    return NO;
}

- (void)saveFavorit:(Favorit *)obj{
    if (obj == nil) {
        return;
    }
    FavorityEntity *oldEntity = [self getFavorityEntityWithItemName:obj.item.itemName];
    if (oldEntity) {
        [oldEntity setItemID: [NSNumber numberWithInteger:[obj.item.itemID integerValue]]];
        [oldEntity setItemName:obj.item.itemName];
        [oldEntity setItemPrice:obj.item.itemPrice];
        [oldEntity setItemImageURLString:obj.item.itemImageURLString];
        [oldEntity setItemClickURLString:obj.item.itemClickURLString];
        [oldEntity setPromotionPrice:obj.item.promotionPrice];
        [oldEntity setTradingVolumeInThirtyDays:obj.item.tradingVolumeInThirtyDays];
        [oldEntity setSortid:[NSNumber numberWithInteger:obj.index]];
        
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
        return;
    }
    FavorityEntity *newEntity= [NSEntityDescription insertNewObjectForEntityForName:@"FavorityEntity"
                                                               inManagedObjectContext:self.managedObjectContext];
    [newEntity setItemID:obj.item.itemID];
    [newEntity setItemName:obj.item.itemName];
    [newEntity setItemPrice:obj.item.itemPrice];
    [newEntity setItemImageURLString:obj.item.itemImageURLString];
    [newEntity setItemClickURLString:obj.item.itemClickURLString];
    [newEntity setPromotionPrice:obj.item.promotionPrice];
    [newEntity setTradingVolumeInThirtyDays:obj.item.tradingVolumeInThirtyDays];
    [newEntity setSortid:[NSNumber numberWithInteger:obj.index]];
    
    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

- (void)favoritItem:(CuzyTBKItem *)item{
    FavorityEntity *entity = [self getFavorityEntityWithItemName:item.itemName];
    if (entity) {
        return;
    }
    FavorityEntity *newEntity= [NSEntityDescription insertNewObjectForEntityForName:@"FavorityEntity"
                                                               inManagedObjectContext:self.managedObjectContext];
    [newEntity setItemID: [NSNumber numberWithInteger:[item.itemID integerValue]]];
    [newEntity setItemName:item.itemName];
    [newEntity setItemPrice:item.itemPrice];
    [newEntity setItemImageURLString:item.itemImageURLString];
    [newEntity setItemClickURLString:item.itemClickURLString];
    [newEntity setPromotionPrice:item.promotionPrice];
    [newEntity setTradingVolumeInThirtyDays:item.tradingVolumeInThirtyDays];
    [newEntity setSortid:[NSNumber numberWithInteger:[self.favorites count]]];
    
    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

- (void)removeItem:(CuzyTBKItem *)item{
    FavorityEntity *entity = [self getFavorityEntityWithItemName:item.itemName];
    if (!entity) {
        return;
    }
    
    [self.managedObjectContext deleteObject:entity];
    for (Favorit *object in self.favorites) {
        if ([object.item.itemName  isEqualToString:item.itemName]) {
            [self.favorites removeObject:object];
            break;
        }
    }
    if ([entity isDeleted]){
        NSError *savingError = nil;
        if ([self.managedObjectContext save:&savingError]){
            //保存，flush到数据库。
            [self reorderFavorites];
        }
        
    }
}

@end
